package xyz.msj.hrm.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.msj.hrm.domain.CoursePromotion;
import xyz.msj.hrm.domain.OrderCoursePromotion;
import xyz.msj.hrm.domain.OrderCoursePromotionDetail;
import xyz.msj.hrm.dto.CoursePromotionDto;
import xyz.msj.hrm.feign.client.RedisFeignClient;
import xyz.msj.hrm.mapper.CoursePromotionMapper;
import xyz.msj.hrm.mapper.OrderCoursePromotionDetailMapper;
import xyz.msj.hrm.mapper.OrderCoursePromotionMapper;
import xyz.msj.hrm.service.ICoursePromotionService;
import xyz.msj.hrm.util.AjaxResult;
import xyz.msj.hrm.util.CodeGenerateUtils;
import xyz.msj.hrm.util.SerializeUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mushengjie
 * @since 2020-09-18
 */
@Service
@Transactional
public class CoursePromotionServiceImpl extends ServiceImpl<CoursePromotionMapper, CoursePromotion> implements ICoursePromotionService {
    //redis
    @Autowired
    private RedisFeignClient redisFeignClient;
    //订单
    @Autowired
    private OrderCoursePromotionMapper orderCoursePromotionMapper;
    //订单详情
    @Autowired
    private OrderCoursePromotionDetailMapper orderCoursePromotionDetailMapper;

    /**
     * 课程促销
     *
     * @param coursePromotionDto
     */
    @Override
    public void promotion(CoursePromotionDto coursePromotionDto) {
        //获取课程id
        Long CourseId = coursePromotionDto.getId();
        //课程促销价格
        float price = coursePromotionDto.getPrice();
        //促销课程数量
        Integer number = coursePromotionDto.getNumber();
        //促销课程开始时间
        Date startTime = coursePromotionDto.getStartTime();
        //促销课程结束时间
        Date endTime = coursePromotionDto.getEndTime();


        //判断redis中是否有该课程了


        //创建一个课程促销对象
        CoursePromotion coursePromotion = new CoursePromotion();
        //促销的课程
        coursePromotion.setCourseId(CourseId);
        /**
         * 课程原价
         */
        coursePromotion.setOldPrice(1000F);

        /**
         * 课程促销价格
         */
        coursePromotion.setPrice(price);
        /**
         * 促销的课程名字
         */
        coursePromotion.setName("SpringCloud 大神");
        /**
         * 促销的课程简介
         */
        coursePromotion.setDescription("带你超神带你飞");
        /**
         * 促销开始时间
         */
        coursePromotion.setStartTime(startTime);
        /**
         * 促销结束时间
         */
        coursePromotion.setEndTime(endTime);
        /**
         * 促销的课程的数量
         */
        coursePromotion.setNumber(number);
        /**
         * 促销状态：0促销未开始，1促销中，2促销过期
         */
        coursePromotion.setState(1);
        /**
         * 课程封面
         */
        coursePromotion.setPic(null);
        //保存促销
        Integer insert = baseMapper.insert(coursePromotion);
        if (insert > 0) {
            //保存到redis (CoursePromotion Promotion:id  ,num)
            AjaxResult ajaxResult = redisFeignClient.hset(CoursePromotion.COURSE_PROMOTION, CoursePromotion.PROMOTION + CourseId, SerializeUtil.serialize(coursePromotion));
            if (!ajaxResult.isSuccess()) {
                throw new RuntimeException("课程促销缓存失败");
            }
        }
    }

    /**
     * 课程促销查询
     */
    @Override
    public List<CoursePromotion> getPromotion() {

        //获取所有缓存数据
        List<byte[]> values = redisFeignClient.hvals(CoursePromotion.COURSE_PROMOTION);
        //用来封装结果的list
        List<CoursePromotion> result  = new ArrayList<>(values.size());
        values.forEach(value ->{
            result.add(((CoursePromotion) SerializeUtil.unserialize(value)));
        });
        System.out.println(result);
        return  result;
    }

    /**
     * 课程促销抢购
     *
     * @param id
     */
    @Override
    public void promotionRush(Long id) {
        if (id == null) {
            throw new RuntimeException("促销课程抢购失败！id为null");
        }
        //根据id修改数据库的促销数量，然后将数据同步到redis
        CoursePromotion coursePromotion = baseMapper.selectByCourseId(id);
        //1．抢购时间是否在有效时间范围
        Date date = new Date();
        if (!(date.getTime() < coursePromotion.getEndTime().getTime()) && !(coursePromotion.getStartTime().getTime() < date.getTime())){
            throw new RuntimeException("促销课程不在抢购时间内");
        }

        //2．抢购的课程状态是否是抢购中 1
        if (!coursePromotion.getState().equals(1)) {
            throw new RuntimeException("促销课程不在抢购中，请持续关注");
        }

        //3．抢购的课程的剩余数量是否 > 0
        if (coursePromotion.getNumber().equals(0)) {
            throw new RuntimeException("促销课程已经被抢购完，请持续关注，稍后推出更加精美课程");
        }
        //1. 保存课程的订单数据到数据库
        promotionRushOrder(coursePromotion);
        //抢购之后数量减一
        coursePromotion.setNumber(coursePromotion.getNumber()-1);
        //更新
        Integer integer = baseMapper.updateById(coursePromotion);
        if (integer > 0) {
            //同步到redis
            AjaxResult ajaxResult = redisFeignClient.hset(CoursePromotion.COURSE_PROMOTION, CoursePromotion.PROMOTION + id, SerializeUtil.serialize(coursePromotion));
            if (!ajaxResult.isSuccess()) {
                throw new RuntimeException("课程促销抢购失败！");
            }
        }


    }

    /**
     * 课程促销抢购订单
     *
     * @param
     * @param coursePromotion
     */
    public void promotionRushOrder(CoursePromotion coursePromotion) {

        //1. 保存课程的订单数据到数据库
        OrderCoursePromotion orderCoursePromotion = new OrderCoursePromotion();

        /**
         * 促销课程ID
         */
        orderCoursePromotion.setCoursePromotionId(coursePromotion.getId());
        /**
         * 订单支付价格
         */
        orderCoursePromotion.setPayPrice(coursePromotion.getPrice());
        /**
         * 购买的课程数量，固定 1
         */
        orderCoursePromotion.setTotalNumber(1);
        /**
         * 订单编号  用户id 1
         */
        orderCoursePromotion.setSn(CodeGenerateUtils.generateOrderSn(1));
        /**
         * 发起支付时间
         */
        orderCoursePromotion.setPayApplyTime(new Date());
        /**
         * 支付成功时间
         */
        orderCoursePromotion.setPayLastTime(DateUtils.addMinutes(new Date(), 15));
        /**
         * 用户ID
         */
        orderCoursePromotion.setUserId(1L);
        /**
         * 订单状态：0待支付，1支付成功，2支付超时  待支付 //2. 订单状态为“待支付”
         */
        orderCoursePromotion.setState(0);
        //保存订单
        Integer integer = orderCoursePromotionMapper.insert(orderCoursePromotion);
        if (integer < 1) {
            throw new RuntimeException("保存订单失败！");
        }

        //创建订单详情对象
        OrderCoursePromotionDetail orderCoursePromotionDetail = new OrderCoursePromotionDetail();
        /**
         * 订单ID
         */
        orderCoursePromotionDetail.setOrderCoursePromotionId(orderCoursePromotion.getId());

        /**
         * 促销课程ID
         */
        orderCoursePromotionDetail.setCoursePromotionId(coursePromotion.getId());
        /**
         * 订单支付价格
         */
        orderCoursePromotionDetail.setPrice(coursePromotion.getPrice());
        /**
         * 购买的课程数量，固定 1
         */
        orderCoursePromotionDetail.setNumber(1);
        //保存订单详情
        Integer updateById = orderCoursePromotionDetailMapper.insert(orderCoursePromotionDetail);
        if (updateById < 1) {
            throw new RuntimeException("保存订单详情失败！");
        }


    }
}
